package com.yhh.zhongdian.view.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.yhh.basemvplib.impl.IPresenter;
import com.yhh.zhongdian.MyApplication;
import com.yhh.zhongdian.R;
import com.yhh.zhongdian.base.MBaseActivity;
import com.yhh.zhongdian.base.observer.MySingleObserver;
import com.yhh.zhongdian.help.VersionCheckHelper;
import com.yhh.zhongdian.utils.RxUtils;
import com.yhh.zhongdian.utils.theme.ThemeStore;
import com.yhh.zhongdian.widget.modialog.MoDialogHUD;

import java.util.Calendar;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
import io.reactivex.Single;
import io.reactivex.SingleOnSubscribe;

/**
 * Created by GKF on 2017/12/15.
 * 关于
 */

public class AboutActivity extends MBaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    // 版本
    @BindView(R.id.tv_version)
    TextView tvVersion;

    @BindView(R.id.tv_author)
    TextView tvAuthor;

    @BindView(R.id.iv_logo)
    AppCompatImageView ivLogo;

    // 帮助
    @BindView(R.id.vw_help)
    LinearLayout llHelp;

    // 评分
    @BindView(R.id.vw_scoring)
    LinearLayout vwScoring;

    // 免责
    @BindView(R.id.vw_disclaimer)
    LinearLayout vwDisclaimer;

    @BindView(R.id.ll_content)
    LinearLayout llContent;

    // 邮件
    @BindView(R.id.vw_mail)
    LinearLayout vwMail;

    // 检查更新
    @BindView(R.id.vw_update)
    LinearLayout vwUpdate;

    // qq
    @BindView(R.id.vw_qq)
    LinearLayout vwQq;

    // 分享
    @BindView(R.id.vw_share)
    LinearLayout vwShare;

    private MoDialogHUD moDialogHUD;
    private String[][] allQQ = new String[][]{
            {"①终点交流群", "②终点交流群", "③终点交流群", "⑤终点内测群"},
            {"2RzbdP2Xkt2t3JHgVwOXGEHGQw-_JR6t", "L1xrZH8v1wJ6N4kq9jpqdbSyPqG2SIcU", "Y23FRbAvBsDMqfy55sg1ceAhcbs7n_7y", "qW4g0dsfZ12b9VrLIsP_gUmURaQ7f_Bx"},
            {"935819760", "1077730188", "1077740834", "1077685545"}
    };

    public static void startThis(Context context) {
        Intent intent = new Intent(context, AboutActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected IPresenter initInjector() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onCreateActivity() {
        getWindow().getDecorView().setBackgroundColor(ThemeStore.backgroundColor(this));
        setContentView(R.layout.activity_about);
    }

    @Override
    protected void initData() {
        moDialogHUD = new MoDialogHUD(this);
    }

    @Override
    protected void bindView() {
        ButterKnife.bind(this);
        this.setSupportActionBar(toolbar);
        setupActionBar();
        tvVersion.setText(getString(R.string.version_name, MyApplication.getVersionName()));
        tvAuthor.setText(String.format("@%d %s", Calendar.getInstance().get(Calendar.YEAR), getString(R.string.app_name)));
//        ivLogo.setColorFilter(ThemeStore.primaryColor(this));
    }

    @Override
    protected void bindEvent() {
        vwScoring.setOnClickListener(view -> openIntent(Intent.ACTION_VIEW, "market://details?id=" + getPackageName()));
        vwMail.setOnClickListener(view -> openIntent(Intent.ACTION_SENDTO, "mailto:3302797840@qq.com"));
        // 帮助页面
        llHelp.setOnClickListener(view -> openIntent(Intent.ACTION_VIEW, getString(R.string.help_url)));
        // 免责声明
//        vwDisclaimer.setOnClickListener(view -> moDialogHUD.showAssetMarkdown("disclaimer.md"));
        vwDisclaimer.setOnClickListener(view -> DisclaimerActivity.startThis(this));
        // 检测更新
        vwUpdate.setOnClickListener(view ->
                {
                    toast("检测更新中...", Toast.LENGTH_SHORT, 0);
                    VersionCheckHelper.needUpdate(this);
                }
        );

        vwQq.setOnClickListener(view -> {
            PopupMenu popupMenu = new PopupMenu(AboutActivity.this, view);
            for (String qq : allQQ[0]) {
                popupMenu.getMenu().add(qq);
            }
            popupMenu.setOnMenuItemClickListener(menuItem -> {
                joinGroup(menuItem.getTitle().toString());
                return true;
            });
            popupMenu.show();
        });

        vwShare.setOnClickListener(view -> {
            String url = getString(R.string.release_url);
            Single.create((SingleOnSubscribe<Bitmap>) emitter -> {
                QRCodeEncoder.HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                Bitmap bitmap = QRCodeEncoder.syncEncodeQRCode(url, 600);
                emitter.onSuccess(bitmap);
            }).compose(RxUtils::toSimpleSingle)
                    .subscribe(new MySingleObserver<Bitmap>() {
                        @Override
                        public void onSuccess(Bitmap bitmap) {
                            if (bitmap != null) {
                                moDialogHUD.showImageText(bitmap, "终点看书下载主页");
                            }
                        }
                    });
        });
    }

    private void joinGroup(String name) {
        for (int i = 0; i < allQQ[0].length; i++) {
            if (name.equals(allQQ[0][i])) {
                if (joinQQGroupError(allQQ[1][i])) {
                    copyName(allQQ[2][i]);
                }
                break;
            }
        }
    }

    private void copyName(String name) {
        ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText(null, name);
        if (clipboard != null) {
            clipboard.setPrimaryClip(clipData);
            toast(R.string.copy_complete);
        }
    }

    /****************
     *
     * 发起添加群流程。群号：终点看书内测群(1077685545) 的 key 为： qW4g0dsfZ12b9VrLIsP_gUmURaQ7f_Bx
     * 调用 joinQQGroup(qW4g0dsfZ12b9VrLIsP_gUmURaQ7f_Bx) 即可发起手Q客户端申请加群 终点看书内测群(1077685545)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回fals表示呼起失败
     ******************/
    public boolean joinQQGroupError(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }

    void openIntent(String intentName, String address) {
        try {
            Intent intent = new Intent(intentName);
            intent.setData(Uri.parse(address));
            startActivity(intent);
        } catch (Exception e) {
            toast(R.string.can_not_open, ERROR);
        }
    }

    //设置ToolBar
    private void setupActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle(R.string.about);
        }
    }

    //菜单
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Boolean mo = moDialogHUD.onKeyDown(keyCode, event);
        return mo || super.onKeyDown(keyCode, event);
    }

}
